#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>


struct sockaddr_in server_addr;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int c = 0; // 成功请求的统计

void *send_task(void *arg){
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if(connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == 0){
    
        if(send(sock, "Test", 4,0) > 0){
            char temp[10] = "";
          
            if(recv(sock, temp, 10,0) > 0){
                if(strncmp(temp, "Test", 4) == 0){
                    // pthread_mutex_lock(&lock);
                    c ++;
                    // pthread_mutex_unlock(&lock);
                }
            }
            
        } 
    }
    close(sock);
    return NULL;
}

// ./ab2 10000
int main(int argc, char const *argv[])
{
    if(argc != 2) return -1;

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8080);
    server_addr.sin_addr.s_addr = inet_addr("10.35.161.29");
    
    int n = atoi(argv[1]); 

    pthread_t **tids = (pthread_t **)calloc(n, sizeof(pthread_t *));
    for(int i=0;i<n;i++){
        tids[i] = (pthread_t *)malloc(sizeof(pthread_t));
    }

    time_t start_ = time(NULL);
    for(int i=0;i<n;i++){
        // printf("tids[%d] = %p\n", i, tids[i]);
        pthread_create(tids[i], NULL, send_task, NULL);
       
    }

    
    for(int i=0;i<n;i++){
        pthread_join(*(tids[i]), NULL);
    }
    time_t end_ = time(NULL);

    for(int i=0;i<n;i++){
        free(tids[i]);
    }
    free(tids);

    printf("成功请求数量： %d, 成功率: %.1f %%,  总时长： %ld s\n",c,
                     (float)c*100/n,   end_ - start_);

    return 0;
}
